package com.hjz.hongbaotest.activity;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;
import com.hjz.hongbaotest.R;
import com.hjz.hongbaotest.model.DataList;
import com.hjz.hongbaotest.view.SelectPopupWindow;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback ,View.OnClickListener{

    private static String TAG=MainActivity.class.getName();

    private MapView map_view;
    private BaiduMap mBaiduMap;
    //当前位置经纬度
    private double latitude;
    private double longitude;
    private double clickLongitude;  //点击地图获得的纬度
    private double clickLatitude;   //点击地图获得的经度
    private LocationClient mLocClient;
    private boolean isFirstLoc = true;  //是否第一次定位
    private static final int BAIDU_READ_PHONE_STATE = 100;
    private Button btn_caozuo;
    private SelectPopupWindow mSelectPopupWindow;
    private ImageView mImageView, mv_cacel;
    private SelectPopupWindow mPopupWindow;
    DataList.ListBean listBean;
    String name =null;
    String isLogin = null;
    String sessionId = null;
    private  boolean isSelect=false; //是否选择地址
    String address=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        //注意该方法要再setContentView方法之前实现
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        map_view = (MapView) findViewById(R.id.map_view);
        btn_caozuo= (Button) findViewById(R.id.btn_caozuo);
        btn_caozuo.setOnClickListener(this);
        //实例化一个地理编码查询对象
        if (Build.VERSION.SDK_INT >= 23) {
            showContacts();
        } else {
            initMap();
        }
    }

    private void initMap() {

        mBaiduMap = map_view.getMap();
        mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, null));

        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(new MyLocationListener());
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();

        //点击地图任何一处增加标志物
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {

                    clickLatitude = latLng.latitude;
                    clickLongitude = latLng.longitude;

                    BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.map);
                    mBaiduMap.clear();
//
                LatLng point = new LatLng(clickLatitude, clickLongitude);
                // 构建MarkerOption，用于在地图上添加Marker
                MarkerOptions options = new MarkerOptions().position(point)
                        .icon(bitmap);
                // 在地图上添加Marker，并显示
                mBaiduMap.addOverlay(options);

            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });

        //点击覆盖物maker
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {

                //从marker中获取info信息
                Bundle bundle = marker.getExtraInfo();
                listBean = (DataList.ListBean) bundle.getSerializable("listBean");
                SharedPreferences share = getSharedPreferences("user", MODE_PRIVATE);
                name = share.getString("name", "");
                isLogin = share.getString("isLogin", "");
                sessionId = share.getString("sessionId", "");
                showPopu();
                return true;
            }
        });

        getData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_caozuo:
                toShowPop();
                break;
        }
    }

    private TextView tv_refrsh_map,tv_fa_hongbao,tv_cacel;
    private void toShowPop() {

        //实例化SelectPicPopupWindow
        mSelectPopupWindow = new SelectPopupWindow(MainActivity.this, itemsOnClick, R.layout.pop_view_layout,R.id.fa_red);
        //显示窗口
        mSelectPopupWindow.showAtLocation(MainActivity.this.findViewById(R.id.activity_main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
        tv_refrsh_map= (TextView) mSelectPopupWindow.getContentView().findViewById(R.id.tv_refrsh_map);
        tv_fa_hongbao= (TextView) mSelectPopupWindow.getContentView().findViewById(R.id.tv_fa_hongbao);
        tv_cacel= (TextView) mSelectPopupWindow.getContentView().findViewById(R.id.tv_cacel);
        tv_refrsh_map.setOnClickListener(itemsOnClick);
        tv_fa_hongbao.setOnClickListener(itemsOnClick);
        tv_cacel.setOnClickListener(itemsOnClick);

    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_refrsh_map:
                    mBaiduMap.clear();
                    clickLatitude=0;
                    clickLongitude=0;
                    getData();
                    mSelectPopupWindow.dismiss();
                    break;
                case R.id.tv_fa_hongbao:

                    if (clickLongitude==0||clickLatitude==0){
                        Toast.makeText(MainActivity.this,"请点击地图选择发放红包地址",Toast.LENGTH_SHORT).show();
                    }else {
                        Intent intent=new Intent(MainActivity.this,HandRedActivity.class);
                        intent.putExtra("clickLatitude",clickLatitude);
                        intent.putExtra("clickLongitude",clickLongitude);
                        startActivity(intent);
                    }

                    mSelectPopupWindow.dismiss();
                    break;
                case R.id.tv_cacel:
                    mSelectPopupWindow.dismiss();
                    break;

                case R.id.iv_qiang:
                    String id=listBean.getId();
                    uploadParm(name, id,sessionId, isLogin);
                    mPopupWindow.dismiss();
                    break;

                case R.id.mv_cacel:
                    mPopupWindow.dismiss();
                    break;

                default:
                    break;
            }
        }
    };

    /**
     * 定位SDK监听函数
     */

    double lat ;
    double lon ;
    private class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            if (location.getLocType() == BDLocation.TypeGpsLocation) {
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\ndirection : ");
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append(location.getDirection());
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\noperationers:");
                sb.append(location.getOperators());
            }
            lat = location.getLatitude();
            lon = location.getLongitude();
//            Log.e("province",location.getProvince()+"");
//            Log.e("city",location.getCity()+"");
//            Log.e("lat", "" + lat);
//            Log.e("lon",""+lon);
//            Log.e("BaiduLocationApiDem", sb.toString());


            // map view 销毁后不在处理新接收的位置
            if (location == null || map_view == null) {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);

            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                //设定中心点坐标
                LatLng cenpt = new LatLng(lat, lon);

                //定义地图状态
                MapStatus mMapStatus = new MapStatus.Builder()
                        .target(cenpt)
                        .zoom(18)
                        .build();
                //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                //改变地图状态
                mBaiduMap.setMapStatus(mMapStatusUpdate);
//

            }
        }

    }

    private void getData() {


        OkGo.<String>get("http://192.168.1.133:8080/redmap/mapDateList.shtml")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("----mapDateList-----", response.body().toString());
                        //创建marker的显示图标
                        BitmapDescriptor bitmap ;
                        //= BitmapDescriptorFactory.fromResource(R.mipmap.logo)
                        LatLng latLng = null;
                        Marker marker;
                        OverlayOptions options;

                        Gson gson = new Gson();

                        DataList dataList = gson.fromJson(response.body(), DataList.class);
                        List<DataList.ListBean> list = dataList.getList();

                        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.maker_layout,null);
                        TextView mText= (TextView) view.findViewById(R.id.tv_marker_text);
                        for (DataList.ListBean listBean : list) {
                            mText.setText(listBean.getName());
                            latitude = Double.parseDouble(listBean.getLatitude());
                            longitude = Double.parseDouble(listBean.getLongitude());

                            latLng = new LatLng(latitude, longitude);
                            //设置marker
                            bitmap= BitmapDescriptorFactory.fromView(view);
                            options = new MarkerOptions()
                                    .position(latLng)//设置位置
                                    .icon(bitmap)
                                    .zIndex(9) // 设置marker所在层级
                                    .draggable(true);

                            //添加marker
                            marker = (Marker) mBaiduMap.addOverlay(options);

                            //使用marker携带info信息，当点击事件的时候可以通过marker获得info信息
                            Bundle bundle = new Bundle();
                            //info必须实现序列化接口
                            bundle.putSerializable("listBean", listBean);
                            marker.setExtraInfo(bundle);
                        }

                        //将地图显示在最后一个marker的位置
                        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
                        mBaiduMap.setMapStatus(msu);

                    }
                });
    }

    //final String name, final String id,final String sessionId, final String isLogin
    private void showPopu() {

        mPopupWindow = new SelectPopupWindow(MainActivity.this, itemsOnClick, R.layout.custom_popup_window,R.id.id_pop_layout);
        //显示窗口
        mPopupWindow.showAtLocation(MainActivity.this.findViewById(R.id.activity_main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置

        mImageView = (ImageView) mPopupWindow.getContentView().findViewById(R.id.iv_qiang);
        mv_cacel = (ImageView) mPopupWindow.getContentView().findViewById(R.id.mv_cacel);


        mImageView.setOnClickListener(itemsOnClick);
        mv_cacel.setOnClickListener(itemsOnClick);
    }


    private void uploadParm(String name, String id,String sessionId,String isLogin) {
        if (isLogin.equals("true")) {

            OkGo.<String>post("http://192.168.1.133:8080/redmap/member/red/payRed.shtml")
                    .params("loginName", name)
                    .params("id", id)
                    .params("sessionId",sessionId)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {

                            Log.e("-----onSuccess----", response.body().toString());
                            try {
                                JSONObject obj = new JSONObject(response.body().toString());
                                String msg = obj.getString("msg");
                                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            Log.e("-----onError----", response.body().toString());
                        }
                    });

        }

    }

    public void showContacts() {
        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getApplicationContext(), "没有权限,请手动开启定位权限", Toast.LENGTH_SHORT).show();
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, BAIDU_READ_PHONE_STATE);
        } else {
            initMap();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case BAIDU_READ_PHONE_STATE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                    initMap();
                } else {
                    // 没有获取到权限，做特殊处理
                    Toast.makeText(getApplicationContext(), "获取位置权限失败，请手动开启", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    private boolean isExit=false;

    Handler mHandler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit=false;
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        map_view.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        map_view.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        map_view.onDestroy();
        //根据 Tag 取消请求
        OkGo.getInstance().cancelTag(TAG);
    }



}
